package com.wpw.dream.annotations;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class AnnotationsParse {
	
	public static String getTableName(Class<?> clazz) {
		Table table = clazz.getAnnotation(Table.class);
		String tableName = null;
		if (table != null) {
			tableName = table.value();
		}
		
		return tableName;
	}
	
	public static List<NameAndType> getClomns(Class<?> clazz) {
		List<NameAndType> list = new ArrayList<>();
		if (clazz.isAnnotationPresent(Table.class)){
			
			Field[] fields = clazz.getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				NameAndType nameAndType = null;
				if (fields[i].isAnnotationPresent(Column.class)) {
					nameAndType = new NameAndType();
					nameAndType.setName(fields[i].getAnnotation(Column.class).value());
					nameAndType.setType(fields[i].getAnnotation(Column.class).type());
				}
				list.add(nameAndType);
			}
			
		}
		return list;
	}
	
	public static String buildSql(Class<?> clazz) {
		String tableName = getTableName(clazz);
		StringBuilder sql = new StringBuilder("insert table ")
							.append(tableName).append("(");
		List<NameAndType> clomns = getClomns(clazz);
		for (int i = 0; i < clomns.size(); i++) {
			if (i < clomns.size() -1)
				sql.append(clomns.get(i).getName()).append("(").append(clomns.get(i).getType()).append("),");
			else
				sql.append(clomns.get(i).getName()).append("(").append(clomns.get(i).getType()).append("))");
		}
		
		return sql.toString();
	}

	public static void main(String[] args) {
		System.out.println(buildSql(User.class));
	}
}

class NameAndType {
	private String name;
	private String type;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	
}
